/**
 * Created by mcbird on 4/16/15.
 */
var mongoose = require('mongoose');
var crypto = require('crypto');
//var ccap = require('ccap');
var express = require('express');
var router = express.Router();

//encrypt text through md5
function md5(text){
	return crypto.createHash('md5').update(text).digest('hex');
}

var Schema = mongoose.Schema;
// Mongoose Schema definition
var UserSchema = new Schema({
	user_email: {
		type: "String",
		required: true
	},
	user_password: {
		type: "String",
		required: true
	}
});
UserSchema.statics.findOneByEmail = function(email, callback) {
	this.find({user_email: new RegExp(email, 'i')}, callback);
};

// Mongoose Model definition
var User = mongoose.model('users', UserSchema);

router.get('/', function(req, res, next) {
	res.render('login', {});
});

router.post('/adduser', function(req, res) {
	var userEmail = req.body.useremail;
	var userPassword = md5(req.body.password);
	
	/*if(req.body.captionText.toLowerCase() != req.session.captionText.toLocaleLowerCase()) {
		res.send({
			success: false,
			msg: '验证码错误'
		});
	}*/

	//判断email是否已被注册
	User.findOneByEmail(userEmail, function(err, result) {
		if(result.length === 0) {
			var newUser = new User({user_email: userEmail, user_password: userPassword});
			newUser.save(function() {
				console.log('添加用户(' + userEmail + ') 成功！');
				res.send({
					success: true
				});
			}, function(err) {
				console.error.bind(console, err);
				res.send({
					success: false
				});
			});
		} else {
			res.send({
				success: false,
				msg: '邮箱已被注册'
			});
		}

	});
});

router.post('/validateuser', function(req, res) {
	var userEmail = req.body.useremail;
	var userPassword = md5(req.body.password);
	User.findOneByEmail(userEmail, function(err, result) {
		if(result.length === 0) {
			res.send({
				success: false,
				msg: '账号不存在'
			});
		} else {
			var _password = result[0]['user_password'];
			if(userPassword === _password) {
				req.session.userEmail = result[0]['user_email'];
				res.send({
					success: true,
					redirectUrl: '/portal'
				});
			} else {
				res.send({
					success: false,
					msg: '密码不正确'
				});
			}
		}

	});
});

/*router.get('/getcaption', function(req, res) {
	var arr = ccap().get();
	req.session.captionText = arr[0];
	var buf = arr[1];
	res.set('Content-Type', 'image/jpeg');
	res.send(buf);
});*/

module.exports = router;